package com.example.demo.demos.web.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.net.URI;
import java.util.HashMap;
import java.util.Map;

public class HttpPostOrGetUtil {

    // 默认超时时间，单位为毫秒
    private static final int TIMEOUT = 5000;

    /**
     *  通用的 POST 请求方法，支持传入 URL， 请求头，参数等
     * @param url
     * @param headers
     * @param params
     * @return
     * @throws Exception
     */
    public static String sendPostRequest(String url, Map<String, String> headers, Map<String, String> params) throws Exception {
        // 创建 HTTP 客户端
        try (CloseableHttpClient client = HttpClients.createDefault()) {

            // 创建 POST 请求
            HttpPost post = new HttpPost(url);

            // 设置请求超时配置
            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectTimeout(TIMEOUT)
                    .setSocketTimeout(TIMEOUT)
                    .build();
            post.setConfig(requestConfig);

            // 将参数转为 JSON 字符串
            ObjectMapper mapper = new ObjectMapper();
            String requestBody = mapper.writeValueAsString(params);

            // 设置请求头
            post.setHeader("Content-Type", "application/json");
            if (headers != null) {
                headers.forEach(post::setHeader);
            }

            // 设置请求体
            StringEntity entity = new StringEntity(requestBody);
            post.setEntity(entity);

            // 发送请求并获取响应
            org.apache.http.HttpResponse response = client.execute(post);
            HttpEntity responseEntity = response.getEntity();

            // 获取响应的内容
            return EntityUtils.toString(responseEntity);
        }
    }

    /**
     * URL 编码的表单数据 POST 请求方法
     * @param url
     * @param headers
     * @param formParams
     * @return
     * @throws Exception
     */
    public static String sendFormPostRequest(String url, Map<String, String> headers, Map<String, String> formParams) throws Exception {
        // 创建 HTTP 客户端
        try (CloseableHttpClient client = HttpClients.createDefault()) {

            // 创建 POST 请求
            HttpPost post = new HttpPost(url);

            // 设置请求超时配置
            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectTimeout(TIMEOUT)
                    .setSocketTimeout(TIMEOUT)
                    .build();
            post.setConfig(requestConfig);

            // 将表单数据转为 URL 编码的字符串
            StringBuilder formData = new StringBuilder();
            for (Map.Entry<String, String> entry : formParams.entrySet()) {
                if (formData.length() > 0) {
                    formData.append("&");
                }
                formData.append(entry.getKey())
                        .append("=")
                        .append(java.net.URLEncoder.encode(entry.getValue(), "UTF-8"));
            }

            // 设置请求头
            post.setHeader("Content-Type", "application/x-www-form-urlencoded");
            if (headers != null) {
                headers.forEach(post::setHeader);
            }

            // 设置请求体
            StringEntity entity = new StringEntity(formData.toString());
            post.setEntity(entity);

            // 发送请求并获取响应
            org.apache.http.HttpResponse response = client.execute(post);
            HttpEntity responseEntity = response.getEntity();

            // 获取响应的内容
            return EntityUtils.toString(responseEntity);
        }
    }

    public static String sendGetRequest(String url, Map<String, String> headers, Map<String, String> params) throws Exception {
        try (CloseableHttpClient client = HttpClients.createDefault()) {
            // 构建URI，并添加请求参数
            URIBuilder uriBuilder = new URIBuilder(url);
            if (params != null) {
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    uriBuilder.addParameter(entry.getKey(), entry.getValue());
                }
            }
            URI uri = uriBuilder.build();

            // 创建HttpGet请求
            HttpGet get = new HttpGet(uri);
            get.setHeader("Content-Type", "application/json");

            // 添加额外的请求头
            if (headers != null) {
                headers.forEach(get::setHeader);
            }

            // 执行请求
            org.apache.http.HttpResponse response = client.execute(get);
            HttpEntity responseEntity = response.getEntity();
            return EntityUtils.toString(responseEntity);
        }

    }


    public static void main(String[] args) {
//        try {
//            String s = sendGetRequest("https://www.baidu.com/?tn=68018901_16_pg", null);
//            System.err.println("s = " + s);
//        } catch (Exception e) {
//            throw new RuntimeException(e);
//        }


        //1.测试post 请求
//       System.out.println(postTest());
//        //2.解析返回json 字符串对象
//        String jsonStr = "{\n" +
//                "\"success\":1,\n" +
//                "\"data\":{\n" +
//                "    \"access_token\": \"access_token\",\n" +
//                "    \"refresh_token\": \"6663211fda1a41f5a1c1fa320d819aaa\",\n" +
//                "\"refresh_expires_in\": \"780260\",\n" +
//                "\"access_expires_in\":10800000000000\n" +
//                "}\n" +
//                "}";
//        ObjectMapper mapper = new ObjectMapper();
//        HnSSoResponseBody responseBody;
//        try {
//            responseBody = mapper.readValue(jsonStr, HnSSoResponseBody.class);
//        } catch (JsonProcessingException e) {
//            throw new RuntimeException(e);
//        }
//        System.out.println(responseBody.getData().getRefreshToken());
//        System.out.println(responseBody);

        //3.解析json 返回data对象测试

//        String jsonDataStr = "{\n" +
//                "    \"success\":1,\n" +
//                "    \"data\":{\n" +
//                "        \"email\":\"\",\n" +
//                "        \"expiration\":\"2021-08-31T17:46:40Z\",\n" +
//                "        \"idcard_no\":\"\",\n" +
//                "        \"is_admin\":2,\n" +
//                "        \"job_title\":\"\",\n" +
//                "        \"oid\":[\n" +
//                "            \"aab674e3-1d51-4bf7-b4bd-8a506287755b\"\n" +
//                "        ],\n" +
//                "        \"created_at\":\"\",\n" +
//                "        \"created_user\":\"\",\n" +
//                "        \"department_name\":[\n" +
//                "            \"煤矿科\"\n" +
//                "        ],\n" +
//                "        \"person_id\":0,\n" +
//                "        \"phone\":\"16666666666\",\n" +
//                "        \"remark\":\"\",\n" +
//                "        \"sequence\":0,\n" +
//                "        \"state\":1,\n" +
//                "        \"updated_at\":\"2021-03-01T17:08:59Z\",\n" +
//                "        \"user_code\":\"\",\n" +
//                "        \"user_id\":\"1111\",\n" +
//                "        \"user_login_name\":\"shf\",\n" +
//                "        \"user_name_pinyin\":\"\",\n" +
//                "        \"user_sex\":\"M\",\n" +
//                "        \"username\":\"尚海峰\",\n" +
//                "        \"org\":[\n" +
//                "            {\n" +
//                "                \"address\":\"\",\n" +
//                "                \"create_user\":\"\",\n" +
//                "                \"created\":\"0001-01-01T00:00:00Z\",\n" +
//                "                \"dep_code\":\"01430801000706000\",\n" +
//                "                \"department_id\":\"aab674e3-1d51-4bf7-b4bd-8a506287755b\",\n" +
//                "                \"department_name\":\"煤矿科\",\n" +
//                "                \"department_order\":\"\",\n" +
//                "                \"description\":\"\",\n" +
//                "                \"display_name\":\"煤矿安全监督管理科\",\n" +
//                "                \"is_normal\":0,\n" +
//                "                \"is_reprot\":0,\n" +
//                "                \"org_full_path\":\"\",\n" +
//                "                \"org_name_pinyin\":\"\",\n" +
//                "                \"org_name_short\":\"\",\n" +
//                "                \"org_type\":\"内设机构\",\n" +
//                "                \"parent_org_no\":\"01430801000000000\",\n" +
//                "                \"parent_id\":\"d21f8ac5-ed99-4185-98fa-779279e34031\",\n" +
//                "                \"phone\":\"\",\n" +
//                "                \"show_order_full\":\"\",\n" +
//                "                \"state\":1,\n" +
//                "                \"status\":0,\n" +
//                "                \"update_user\":\"\"\n" +
//                "            }\n" +
//                "        ],\n" +
//                "        \"person\":{\n" +
//                "            \"bz\":\"\",\n" +
//                "            \"create_user\":\"\",\n" +
//                "            \"created\":\"0001-01-01T00:00:00Z\",\n" +
//                "            \"id\":0,\n" +
//                "            \"idcard\":\"\",\n" +
//                "            \"name\":\"\",\n" +
//                "            \"office_phone\":\"\",\n" +
//                "            \"oid\":\"\",\n" +
//                "            \"order\":0,\n" +
//                "            \"phone\":\"\",\n" +
//                "            \"sex\":0,\n" +
//                "            \"state\":0,\n" +
//                "            \"updated\":\"0001-01-01T00:00:00Z\"\n" +
//                "        }\n" +
//                "    }\n" +
//                "}";
//
//        ObjectMapper objectMapper = new ObjectMapper();
//        HnSSoUserInfoResponseBody hnSSoUserInfoResponseBody;
//        try {
//            hnSSoUserInfoResponseBody = objectMapper.readValue(jsonDataStr, HnSSoUserInfoResponseBody.class);
//        } catch (JsonProcessingException e) {
//            throw new RuntimeException(e);
//        }
//
//        System.out.println("hnSSoUserInfoData = " + hnSSoUserInfoResponseBody);
    }

    public static String postTest(){
        String url ="http://172.16.78.78:9919/auth/me/info";
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("Authorization", "Bearer SAo/d1NHx5ZwGGtmYnyubgMfOmNsHzyDnxKK4vtoIiA=");
        Map<String,String> params =new HashMap<>();
        String s = null;
        try {
            s = sendPostRequest(url, headers, null);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return s;
    }
}
